package com.treasure.hunt.main

import android.content.Intent
import android.net.Uri
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ScreenUtils
import com.module.lemlin.base.loadCircleImage
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.AnimManager
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.app.THApplication
import com.treasure.hunt.entity.Action
import com.treasure.hunt.entity.MainBean
import com.treasure.hunt.entity.TaskSign
import com.treasure.hunt.entity.UserInfo
import com.treasure.hunt.mine.*
import com.treasure.hunt.mode.TaskViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import com.treasure.hunt.popup.DialogHintPopup
import com.treasure.hunt.task.TaskInviteActivity
import kotlinx.android.synthetic.main.fragment_main_mine.*
import org.greenrobot.eventbus.EventBus

class MainMineFragment : ViewModeFragment<TaskViewMode>() {

    companion object {
        fun newInstance(): MainMineFragment {
            return MainMineFragment()
        }
    }

    private var mContactNumber: String? = null

    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = { view, type ->
                hintPopup.dismiss()
                if (mContactNumber.isNullOrEmpty()) {
                    toast("请设置正确的联系方式")
                    return@DialogHintPopup
                }
                if (type == DialogHintPopup.Type.SHOW_PHONE) {
                    val intent = Intent(Intent.ACTION_DIAL)
                    val data: Uri = Uri.parse("tel:${mContactNumber}")
                    intent.data = data
                    startActivity(intent)
                }
            },
            onCancel = { view, type ->
                hintPopup.dismiss()
            })
    }

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = requireContext(), onAnimationEnd = {

            if (it.tag as Boolean) {
                viewModel.taskSignList()
                return@DialogFlopPopup
            }
            if (it.drawable == null)
                return@DialogFlopPopup

            val circleImageView = ImageView(activity)
            val layoutParams = LinearLayout.LayoutParams(
                ConvertUtils.dp2px(50f), ConvertUtils.dp2px(50f)
            )
            circleImageView.layoutParams = layoutParams
            circleImageView.loadRoundImage(it.drawable, radius = 25)

            val animManager: AnimManager = AnimManager.Builder()
                .with(requireActivity())
                .animModule(AnimManager.AnimModule.BIG_CIRCLE)
                .time(1200)
                .listener(object : AnimManager.AnimListener {
                    override fun setAnimBegin(a: AnimManager) {}
                    override fun setAnimEnd(a: AnimManager) {
                        a.stopAnim()
                    }
                })
                .animView(circleImageView)
                .build()
            animManager.startAnim(
                intArrayOf(
                    (ScreenUtils.getAppScreenWidth() / 2) - ConvertUtils.dp2px(25f),
                    ScreenUtils.getAppScreenHeight() / 2
                ), intArrayOf(
                    ScreenUtils.getAppScreenWidth() / 8 * 7,
                    ScreenUtils.getAppScreenHeight()
                )
            )

            val mainBean: MainBean<Action, Any> = MainBean(
                type = Action.GO_MINE
            )
            EventBus.getDefault().post(mainBean)
        }, onDoubled = {
            val maps: MutableMap<String, Any?> = mutableMapOf(
                "advertisement_type" to 5,
                "luck_draw_type" to 7,
                "model_type" to 6,
                "reward_id" to it.id
            )
            viewModel.videoType(maps)
        })
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main_mine

    override fun viewModel(): TaskViewMode {
        return createViewModel()
    }

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(flMainMineBar)

//        rvMainMineCardBody.apply {
//            layoutManager = LinearLayoutManager(requireContext()).apply {
//                orientation = LinearLayoutManager.HORIZONTAL
//            }
//        }.adapter = cardAdapter

        //编辑资料
        tvMineInfo.setOnClickListener {
            MineInfoActivity.open(requireActivity())
        }
        //我的卡包
        flMineCard.setOnClickListener {
            MineCardActivity.open(requireActivity())
        }
        //合成记录
        tvMineMerge.setOnClickListener {
            MineMergeActivity.open(requireActivity())
        }
        //签到有礼
        tvMineSign.setOnClickListener {
            viewModel.taskSignList()
        }
        //邀请好友
        tvMineInvite.setOnClickListener {
            TaskInviteActivity.open(requireActivity())
        }
        //联系客服
        tvMineService.setOnClickListener {
            viewModel.otherGetConfig("service_mobile")
        }
        //意见反馈
        tvMineOpinion.setOnClickListener {
            MineOpinionActivity.open(requireActivity())
        }
        //关于我们
        tvMineAbout.setOnClickListener {
            MineAboutActivity.open(requireActivity())
        }

    }

    override fun initData() {
        viewModel.userInfo()
    }

    override fun onRefreshLoad() {
        super.onRefreshLoad()
        THApplication.userInfo?.let {
            fillData(it)
        }
        viewModel.userInfo()
    }

    override fun initViewMode() {
//        viewModel.taskSignLiveData.observe(viewLifecycleOwner, Observer { response ->
//            if (response.status != Status.SUCCESS)
//                return@Observer
//            response.httpData?.data?.list?.let {
//                signPopup.setFillData(it)
//                    .showPopupWindow()
//            }
//        })

        viewModel.userInfoLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                fillData(it)
            }
        })

        viewModel.otherConfigLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer

            response.httpData?.data?.let {
                mContactNumber = it.content
//                hintPopup.setType(DialogHintPopup.Type.SHOW_PHONE).setText(
//                    textTitle = "联系客服",
//                    textMessage = it.content,
//                    textConfirm = "确认",
//                    textCancel = "取消"
//                )
//                    .showPopupWindow()

                MineConfigActivity.openUrl(requireActivity(), "联系客服", it.content)
            }
        })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            }else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = requireActivity(),codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = requireActivity(),codeId = codeId)
            }
        })


        viewModel.videoTypeLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
        })

        viewModel.rewardVerifyAdLiveData.observe(
            this as LifecycleOwner, Observer { isRewardVerifyAd ->
//                if (!isRewardVerifyAd && !viewModel.isRewardVerifyAdSign)
//                    return@Observer
//                val taskSign: TaskSign = viewModel.taskSignLiveData.value?.httpData?.data
//                    ?: return@Observer
//                val signId: Int = taskSign.list[taskSign.sign_num ?: 0].id
//                val videoLogId:String = viewModel.videoTypeLiveData.value?.httpData?.data?.video_log_id
//                    ?: return@Observer
//                viewModel.taskSign(signId,videoLogId)
//                viewModel.isRewardVerifyAdSign = false
                if (!isRewardVerifyAd)
                    return@Observer
                if (viewModel.isRewardVerifyAdSign) {
                    val taskSign: TaskSign = viewModel.taskSignLiveData.value?.httpData?.data
                        ?: return@Observer
                    val signId: Int = taskSign.list[taskSign.sign_num ?: 0].id
                    val videoLogId:String = viewModel.videoTypeLiveData.value?.httpData?.data?.video_log_id
                        ?: return@Observer
                    viewModel.taskSign(signId,videoLogId)
                    viewModel.isRewardVerifyAdSign = false
                } else {
                    viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                        viewModel.videoEnd(it.video_log_id)
                    }
                }
            })

        viewModel.luckySignLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                flopPopup.fillData(it).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
            }
        })


        viewModel.videoEndLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                if (viewModel.signPopup.isShowing){
                    viewModel.signPopup.dismiss()
                }
            }
        })

        viewModel.viewAdLiveData.observe(viewLifecycleOwner, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })

    }

    private fun fillData(userInfo: UserInfo) {

        THApplication.userInfo = userInfo
        val isHttps: Boolean = userInfo.avatar.substring(0, 5).contains("http") ||
                userInfo.avatar.substring(0, 5).contains("https")
        ivMineUserHeads.loadCircleImage(
            "${if (isHttps) "" else AppConstance.URL_IMAGE}${userInfo.avatar}",
            borderSize = 5,
            borderColor = ColorUtils.getColor(R.color.colorMain)
        )
        tvMineUserName.text = userInfo.nickname
        tvMineUserId.text = "ID:${userInfo.identification_code}  幸运值:${userInfo.lucky}"
        flMineCardNum.text = "${userInfo.cart_num}"
    }

}